package cn.edu.filter;

import cn.edu.util.JwtUtil;
import cn.edu.vo.ResultVO;
import com.alibaba.fastjson.JSON;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author Mr.ma
 */
@Component
public class MyFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //1.获取请求方式:
        String method = request.getMethod();
        String path= request.getRequestURI();
        if("POST".equals(method)&&"/login".equals(path)){
             filterChain.doFilter(request,response);
             return;
        }

        //2.获取请求头信息
        String token = request.getHeader("token");
        if(token!=null&& JwtUtil.verifyToken(token)){
            //把当前的用户和该用户具有的权限放入SecurityContext对象中。
            Map<String, Object> stringObjectMap = JwtUtil.decodeJWT(token);
            String username = (String) stringObjectMap.get("username");
            List<String> list = (List<String>) stringObjectMap.get("authorities");

            Collection<GrantedAuthority> authorities=list.stream().map(item->new SimpleGrantedAuthority(item)).collect(Collectors.toList());

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(username,null,authorities);
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            filterChain.doFilter(request,response);
        }else{
            response.setContentType("json/application;charset=utf-8");
            PrintWriter writer = response.getWriter();
            ResultVO result=new ResultVO(4001,"未登录",null);
            String jsonString = JSON.toJSONString(result);
            writer.print(jsonString);
            writer.flush();
            writer.close();
        }

    }
}
